package com.wlf.controller;

import com.wlf.constant.Constants;
import com.wlf.entity.ApiResponse;
import com.wlf.entity.MqMessage;
import com.wlf.entity.User;
import com.wlf.mq.send.DirectMsgSender;
import com.wlf.service.IMqMessageService;
import com.wlf.service.IUserService;
import com.wlf.service.impl.RedisService;
import com.wlf.util.MqUtils;
import com.wlf.util.SnowflakeIdUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class sendMsgController {

    private static Logger logger = LoggerFactory.getLogger(sendMsgController.class);

    @Autowired
    private DirectMsgSender directMsgSender;

    @Autowired
    private IUserService userService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private IMqMessageService mqMessageService;

    @Value("${utruck.config.api.max-size}")
    private Integer maxSize;

    @Autowired
    private RedissonClient redissonClient;

    @GetMapping("/sendmsg")
    public ApiResponse<String> sendMsg(){
        String msg ="";
        RLock lock =null;
        try{
            String id = SnowflakeIdUtils.getId();
            lock=redissonClient.getFairLock(id);
            lock.lock(10, TimeUnit.SECONDS);

            String userName ="rabbitmq_"+id;
            String passWord ="password_"+id;
            int age =18;
            User user = this.getUser(id,age,userName,passWord);
            msg = com.alibaba.fastjson.JSONObject.toJSONString(user);
            //存入redis
            redisService.set(id,msg,60*60*4);
            MqMessage mqMessage = this.getMqMessage(id,Constants.MESSAGETYPE_ORDER,id,msg,msg);
            mqMessageService.insert(mqMessage);
            //发送mq
            directMsgSender.send(msg, MqUtils.calcQueueIndex(maxSize,id));
            //发送邮件
          /* MailUtil mailUtil = new MailUtil();
          mailUtil.sendEmail(Constants.SENT_EMAIL_FROM_TO,msg);*/
        }catch (Exception e){
            logger.info(e.getMessage(),e);
        }finally {
            try{
                if(null != lock){
                    lock.unlock();
                }
            }catch (Exception e){
                logger.error("redisson 锁已经被释放，当前线程:{}",Thread.currentThread().getId());
            }
        }
        return   ApiResponse.success(Constants.RESPONSE_OK,Constants.RESPONSE_MESSAGE,msg);
    }

    @GetMapping("/sendApiMsg")
    public ApiResponse<String> sendApiMsg(){
        ApiResponse<String> response = new ApiResponse<>();
        String id = SnowflakeIdUtils.getId();
        String userName ="rabbitmq_"+id;
        String passWord ="password_"+id;
        int age =18;
        User user = this.getUser(id,age,userName,passWord);
        String msg = com.alibaba.fastjson.JSONObject.toJSONString(user);
        user = directMsgSender.sendOrderAuthQueue(msg,id,maxSize);
        msg = com.alibaba.fastjson.JSONObject.toJSONString(user);
        return   ApiResponse.success(Constants.RESPONSE_OK,Constants.RESPONSE_MESSAGE,msg);
    }


    private  User getUser(String id,int age,String userName,String passWord){
        User user = new User();
        user.setId(id);
        user.setAge(age);
        user.setUsername(userName);
        user.setPassword(passWord);
        return user;
    }

    private MqMessage getMqMessage(String id,String messageType,String businessId,String messageBody,String extData) {

        MqMessage mqMessage = new MqMessage();
        mqMessage.setId(id);
        mqMessage.setMessageId(UUID.randomUUID().toString());
        mqMessage.setCreatedTime(new Date());
        mqMessage.setCreatedBy(1);
        mqMessage.setUpdatedBy(1);
        mqMessage.setUpdatedTime(new Date());
        mqMessage.setMessageType(messageType);
        mqMessage.setBusinessId(businessId);
        mqMessage.setMessageBody(messageBody);
        mqMessage.setExtData(extData);
        mqMessage.setIsCustomer(Constants.ZERO);
        mqMessage.setDeleted(Constants.DELETED);

        return mqMessage;
    }
}
